package com.ds.infrastructure.hyperspace.console.dto.apirouter;

import com.alibaba.fastjson.annotation.JSONField;
import com.ds.infrastructure.hyperspace.console.dto.configdata.PipelinesDTO;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: yaozhendong
 * @create: 2019-09-20 16:12
 **/
@Data
@NoArgsConstructor
public class ApiRouterPipelinesDTO implements Serializable {
    @JSONField(name = "entryEndpoint")
    private String entryEndpoint;
    @JSONField(name = "preFlow")
    private List<ApiRouterPreflowDTO> preFlow = new ArrayList<>();
    @JSONField(name = "targetEndpoint")
    private String targetEndpoint;
    @JSONField(name = "postFlow")
    private List<ApiRouterPreflowDTO> postFlow = new ArrayList<>();

    public static ApiRouterPipelinesDTO toApiRouter(PipelinesDTO dto) {
        ApiRouterPipelinesDTO apiRouterPipelinesDTO = new ApiRouterPipelinesDTO();
        apiRouterPipelinesDTO.setEntryEndpoint(dto.getEntryendpoint());
        apiRouterPipelinesDTO.setTargetEndpoint(dto.getTargetendpoint());
        addPreFlowDTO(dto, apiRouterPipelinesDTO);
        addPostFlowDTO(dto, apiRouterPipelinesDTO);
        return apiRouterPipelinesDTO;
    }

    private static void addPostFlowDTO(PipelinesDTO dto, ApiRouterPipelinesDTO apiRouterPipelinesDTO) {
        if (dto.getPostflow() == null || dto.getPostflow().isEmpty()) {
            return;
        }
        List<ApiRouterPreflowDTO> apiRouterPostflowDTOList = new ArrayList<>();
        dto.getPostflow().forEach(item -> apiRouterPostflowDTOList.add(ApiRouterPreflowDTO.toApiRouter(item)));
        apiRouterPipelinesDTO.setPostFlow(apiRouterPostflowDTOList);
    }

    private static void addPreFlowDTO(PipelinesDTO dto, ApiRouterPipelinesDTO apiRouterPipelinesDTO) {
        if (dto.getPreflow() == null || dto.getPreflow().isEmpty()) {
            return;
        }
        List<ApiRouterPreflowDTO> apiRouterPreflowDTOList = new ArrayList<>();
        dto.getPreflow().forEach(item -> apiRouterPreflowDTOList.add(ApiRouterPreflowDTO.toApiRouter(item)));
        apiRouterPipelinesDTO.setPreFlow(apiRouterPreflowDTOList);
    }
}
